import './index.css';
import {useState} from 'react';

function Square({value, onSquareClick, highlight}) { // 添加一个新的prop来表示是否需要高亮

    return (
        <button className={`square ${highlight ? 'highlight' : ''}`} // 如果需要高亮，添加一个新的类名
                onClick={onSquareClick}>
            {value}
        </button>
    )
}

function Board({xIsNext, squares, onPlay}) {

    const result = calculateWinner(squares);
    const winner = result ? result.winner : null;
    const winningLine = result ? result.line : []; // 赢得游戏的线条
    let status;
    if (winner) {
        status = 'Winner: ' + winner;
    } else {
        status = 'Next player: ' + (xIsNext ? 'X' : 'O');
    }

    function handleClick(i) {
        if (squares[i] || calculateWinner(squares)) {
            // console.log('squares',calculateWinner(squares));
            return;
        }
        const nextSquares = squares.slice();
        if (xIsNext) {
            nextSquares[i] = 'X';
        } else {
            nextSquares[i] = 'O';
        }
        onPlay(nextSquares);
    }

    function calculateWinner(squares) {
        const lines = [
            [0, 1, 2],
            [3, 4, 5],
            [6, 7, 8],
            [1, 4, 7],
            [2, 5, 8],
            [0, 3, 6],
            [0, 4, 8],
            [2, 4, 6]
        ];
        for (let i = 0; i < lines.length; i++) {
            const [a, b, c] = lines[i];
            const isNull = squares.some((item) => item === null);
            if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
                return {winner: squares[a], line: lines[i]}; // 返回赢家和赢得游戏的线条
            } else if (!isNull) {
                return {winner: 'peace', line: []};
            }
        }
        return null;
    }

    const btns = [[0, 1, 2], [3, 4, 5], [6, 7, 8]];
    const btnArr = btns.map((btn) => (
        <div key={btn} className='board-row'>
            {btn.map((b) => (
                <Square key={b}
                        value={squares[b]}
                        onSquareClick={() => handleClick(b)}
                        highlight={winningLine.includes(b)} // 如果这个方格在赢得游戏的线条上，高亮它
                />
            ))}
        </div>
    ))

    return (
        <div className="container">
            <div className="status">{status}</div>
            {btnArr}
        </div>
    )
}


export default function Game() {
    const [history, setHistory] = useState([Array(9).fill(null)]);
    const [currentMove, setCurrentMove] = useState(0);
    const [isAscending, setIsAscending] = useState(true); // 新增状态

    const xIsNext = (currentMove % 2) === 0;
    const currentSquares = history[currentMove];

    function handlePlay(nextSquares) {
        const nextHistory = [...history.slice(0, currentMove + 1), nextSquares];
        //找到nextSquares对比currentSquares新增的值的位置
        const diff = nextSquares.findIndex((item, index) => item !== currentSquares[index]);
        console.log('diff', diff);

        setHistory(nextHistory);
        setCurrentMove(nextHistory.length - 1);
    }

    function jumpTo(nextMove) {
        setCurrentMove(nextMove);
    }

    function handleToggle(moves) {
        setIsAscending(!isAscending); // 切换排序方式
    }

    let moves = history.map((squares, move) => {
        let desc;
        desc = 'you are at move #' + move;
        let arr1 = history[move];
        let arr2 = history[move - 1];
        if (move > 0) {
            let diff = arr1.findIndex((item, index) => item !== arr2[index]);
            console.log('diff', diff);
            let row = Math.floor(diff / 3) + 1;
            let col = diff % 3 + 1;
            desc += `(${row},${col})`;
        }

        return (
            <li key={move}>
                <button onClick={() => jumpTo(move)}>{desc}</button>
            </li>
        )
    })
    // let moves = history.map((squares,move)=>{
    //   let desc;
    //   desc = 'you are at move #' + move;

    //   return (
    //     <li key={move}>
    //       <button onClick={()=>jumpTo(move)}>{desc}</button>
    //     </li>
    //   )
    // })
    if (!isAscending) {
        moves = moves.reverse(); // 如果不是升序，反转列表
        console.log(moves);
    }


    return (
        <div className="game">
            <div className="game-board">
                <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay}/>
            </div>
            <div className="game-info">
                <div>status</div>
                <button onClick={handleToggle}>toggle</button>
                <ol>{moves}</ol>
            </div>
        </div>
    )
}
